import React from "react";

import {Card,Divider,Radio,Checkbox,Row,Col,Table,List,InputNumber,Select, Input,Button} from 'antd';

import { ajax,batchAjax, inArray,openErrorNotification, openSuccessNotification, openInfoNotification,showResultMessage, isEmpty,isNotNull, isNull } from '../../common';

import { getUIList } from '../../uiConfig';

import UIActionBar from '../../uicomponents/UIActionBar';

import UIIcon from '../../uicomponents/UIIcon';

import UIToolbar from '../../uicomponents/UIToolbar';

import CourseDefineSelect from './CourseDefineSelect';
import { now } from "moment";

const Option = Select.Option;
/**
 * 课程价格配置
 */
export default class CoursePriceConfigPanel extends React.Component{

    constructor(props) {
        super(props);
		this.state = {
            campusSelectValue : 'allCampus',
            chargeModelSelectValue : 'by_lesson',
            campusList : [],
            campusCheckedList : [],
            coursePriceData : [{
                key : 0,
                campus : "全部校区",
                coursePrice : [
                    {chargeModel : 'by_lesson',priceUnit : '', ammount : 1,price : 100}
                ],
            }],
            unitTimeList : getUIList('ProductUI:unitTime'),
		}
    }
    
    componentDidMount(){
        const course = this.props.location.state.course;

        batchAjax(['EDUCATION/courseManage/getCoursePrice','EDUCATION/campus/list'],[{courseId : course.id},{}],(datas) => {

            let campusSelectValue = 'allCampus';

            let chargeModelSelectValue = 'by_lesson';

            const campusCheckedList = datas[0].map(row => {
                if(row.key === 0){
                    campusSelectValue = 'allCampus';
                }
                else{
                    campusSelectValue = 'campusList';
                }
                chargeModelSelectValue = row.coursePrice[0].chargeModel;
                return row.key;
            });

            const stateMap = {
                campusList : datas[1],
                campusCheckedList : campusCheckedList,
                campusSelectValue : campusSelectValue,
                chargeModelSelectValue : chargeModelSelectValue,
            }

            if(datas[0].length !== 0){
                stateMap['coursePriceData'] = datas[0];
            }

            this.setState(stateMap);
        });
    }

    changeCourseDefine = (value) => {

        const {history,location} = this.props;

        ajax('EDUCATION/courseManage/getById',{id : value.key},(data) => {
           history.push(location.pathname, {course : data});
        });
    }

    onCampusSelecChange = e => {

        const {chargeModelSelectValue} = this.state

        if('campusList' === e.target.value){
            
            this.setState({'coursePriceData':[]});
        }
        else{
            let newCoursePriceData = [];

            newCoursePriceData.push({
                key : 0,
                campus : "全部校区",
                coursePrice : [{
                    chargeModel : chargeModelSelectValue,priceUnit : '', ammount : 1,price : 100
                }],
            });

            this.setState({'coursePriceData':newCoursePriceData});
        }
        
        this.setState({
            campusSelectValue: e.target.value,
        });
    };

    onChargeModelSelecChange = e => {

        let coursePriceData = this.state.coursePriceData;

        coursePriceData.map(priceItem => {
            priceItem.coursePrice.map(item => {
                item.chargeModel = e.target.value;
            })
        });

        this.setState({
            chargeModelSelectValue: e.target.value,
            coursePriceData : coursePriceData,
        });
    }

    onCampusChooserChange = checkedValues => {
        let checkedCampusList = checkedValues;
        
        const {campusList,coursePriceData,chargeModelSelectValue} = this.state;

        let newCoursePriceData = [];

        campusList.map(campus => {
            if(inArray(campus.id,checkedCampusList) != -1){
                newCoursePriceData.push({
                    key : campus.id,
                    campus : campus.campusName,
                    coursePrice : [{
                        chargeModel : chargeModelSelectValue,priceUnit : '', ammount : 1,price : 100
                    }],
                });
            }
        });

        this.setState({'coursePriceData':newCoursePriceData});
    };

    showCampusChooser = (campusList) => {

        return campusList.map(campusItem => {
            return <Col key={campusItem.id + "Col"} span={4}><Checkbox key={campusItem.id} value={campusItem.id}>{campusItem.campusName}</Checkbox></Col>
        });
    }

    addPriceItemClick = (row) => {
    
        let coursePriceData = this.state.coursePriceData;

        const {chargeModelSelectValue} = this.state;

        coursePriceData.map(priceItem => {
            if(priceItem.key === row.key){
                priceItem.coursePrice.push({
                    chargeModel : chargeModelSelectValue,priceUnit : '', ammount : 1,price : 100
                });
            }
        });

        this.setState({
            coursePriceData : coursePriceData,
        });
    }

    removePriceItemClick = (row,removeIndex) => {

        let coursePriceData = this.state.coursePriceData;

        const {chargeModelSelectValue} = this.state;

        coursePriceData.map((priceItem ,index)=> {
            if(priceItem.key === row.key){
                priceItem.coursePrice.splice(removeIndex,1);
            }
        });

        this.setState({
            coursePriceData : coursePriceData,
        });
    }

    onAmmountInputChange = (e,row,index) => {
        const { value } = e.target;
        let coursePriceData = this.state.coursePriceData;
        const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
        if ((!Number.isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            row.coursePrice[index].ammount = value;
        }
    }

    onPriceInputChange = (e,row,index) => {
        const { value } = e.target;
        let coursePriceData = this.state.coursePriceData;
        const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
        if ((!Number.isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            row.coursePrice[index].price = value;
        }
    }

    onUnitTimeChange = (value,row,index) => {

        let coursePriceData = this.state.coursePriceData;
        
        row.coursePrice[index].priceUnit = value;
    }

    actionHandler = (actionEvent) => {

        const {campusList,coursePriceData} = this.state;

        const course = this.props.location.state.course;

        return {
			doSave: () => {

                if(coursePriceData.length === 0){
                    openInfoNotification("请先设置课程费用，再进行保存");
                    return;
                }

                ajax('EDUCATION/courseManage/saveCoursePrice/' + course.id ,coursePriceData,(data) => {
                    if(data.hasError){
                        openErrorNotification("保存失败:" + data.message);
                    }
                    else{
                        openSuccessNotification("保存完成");
                    }
                },'application/json');
            },
        }
    }

    render(){

        const {campusList,coursePriceData,unitTimeList,campusCheckedList} = this.state;

        const coursePriceCardProps = {
            title: <span> <UIIcon icon={'yen-sign'} /> {'设置 [' + this.props.location.state.course.courseName + '] 费用'} </span>,
            extra: <React.Fragment><UIToolbar actionGroupId="ProductUI:saveActionGroup" actionHandler={this.actionHandler}/> <Divider type="vertical" /> <UIActionBar {...this.props} actionGroupId='goBackActionGroup' actionHandler={() => { }} /></React.Fragment>,
            ref : (inst) => { this.coursePriceCardRef = inst }
        };

        const unitTimeOptions = unitTimeList.listData.map((data) => {
            return (<Option key={data.data} value={data.data}>{data.label}</Option>);
        });

        const unitTimeSelect = (row,index) => {
            let priceUnit = row.coursePrice[index].priceUnit;
            return (
                <Select defaultValue={isEmpty(priceUnit) ? unitTimeList.listData[0].data : priceUnit} onChange={value => this.onUnitTimeChange(value,row,index)} size="small" style={{ width: 70 }}>
                    {unitTimeOptions}
                </Select>
            );
        }

        const columns = [
            {
                title: '校区',
                dataIndex: 'campus',
                width: '20%',
                render: (text, row, index) => {
                    return text;
                }
            },
            {
                title: '定价标准',
                dataIndex: 'coursePrice',
                render: (text, row, index) => {
                    return (
                        <List
                            dataSource={row.coursePrice}
                            split={false}
                            size="small"
                            renderItem={(item,index) => (
                                <List.Item>
                                    <Row >
                                        <Col span={1}></Col>
                                        <Col span={4}>{ item.chargeModel === 'by_lesson' ? '按课时:' : item.chargeModel === 'by_term' ? '按期:' : '按时间:' }</Col>
                                        <Col span={4}><Input size="small" key={now.toString + 'Label'}  defaultValue={item.chargeModel === 'by_unit_time' ? 1 : item.ammount} disabled={item.chargeModel === 'by_unit_time'} onChange={ e => this.onAmmountInputChange(e,row,index)}/></Col>
                                        <Col span={1}></Col>
                                        <Col span={4}>{ item.chargeModel === 'by_lesson' ? '课时' : item.chargeModel === 'by_term' ? '期' : item.chargeModel === 'by_unit_time' ? unitTimeSelect(row,index) : '' } = </Col>
                                        <Col span={4}><Input size="small" key={now.toString + 'Label'} defaultValue={item.price}  onChange={e => this.onPriceInputChange(e,row,index)}/></Col>
                                        <Col span={2}>元{item.chargeModel === 'by_term' ? '/期' : ''}</Col>
                                        <Col span={2}><Button type="link" size="small" icon="plus-circle" onClick={event => this.addPriceItemClick(row) }></Button></Col>
                                        <Col span={2}><Button type="link" size="small" icon="minus-circle" disabled={index === 0} onClick={event => this.removePriceItemClick(row,index) }></Button></Col>
                                    </Row>    
                                </List.Item>
                            )}
                            />
                    );
                }
            },
        ];

        return (
            
             <Card {...coursePriceCardProps} >
                <Divider orientation="left">收费模式</Divider> 
                <Radio.Group onChange={this.onChargeModelSelecChange} value={this.state.chargeModelSelectValue}>
                    <Radio value={'by_lesson'}>
                    按课时
                    </Radio>
                    <Radio value={'by_term'}>
                    按  期
                    </Radio>
                    <Radio value={'by_unit_time'}>
                    按时间
                    </Radio>
                </Radio.Group>
                <Divider orientation="left">开课校区</Divider>
                <Radio.Group onChange={this.onCampusSelecChange} value={this.state.campusSelectValue}>
                    <Radio value={'allCampus'}>
                    全部校区
                    </Radio>
                    <Radio value={'campusList'}>
                    指定校区
                    </Radio>
                </Radio.Group>
                {this.state.campusSelectValue === 'campusList' ? 
                    <React.Fragment>
                        <Divider dashed />
                        <Checkbox.Group defaultValue={campusCheckedList} style={{ width: '100%' }} onChange={this.onCampusChooserChange}>
                            <Row>
                                {this.showCampusChooser(campusList)}
                            </Row>
                        </Checkbox.Group>
                    </React.Fragment>
                    : null}
                <Divider orientation="left">定价标准</Divider>
                <Table size="small" pagination={false} columns={columns} dataSource={coursePriceData} bordered></Table>
            </Card>
        );
    }
}